import argparse
import os
from pathlib import Path
from dyva.batch_analyzer import VideoBatchAnalyzer

ORIGINAL_DIR = r"S:\orignV"
COMPRESSED_DIR = r"S:\compressedV"


def parse_args():
    p = argparse.ArgumentParser(description='按清单补跑缺失视频')
    p.add_argument('--list', default='tools/missing_videos_all.txt', help='缺失视频清单路径')
    p.add_argument('--output-dir', default='results', help='输出目录')
    p.add_argument('--config', default='config/categories_example.txt', help='类目表配置文件路径')
    p.add_argument('--api-key', default=None, help='智谱 API Key（可用环境变量 ZHIPU_API_KEY 替代）')
    p.add_argument('--workers', type=int, default=3, help='并发线程数，建议 ≤ 5')
    return p.parse_args()


def normalize_paths(paths):
    def is_compressed(name: str) -> bool:
        return name.lower().endswith('_compressed.mp4')
    normalized = []
    for p in paths:
        base = os.path.basename(p)
        if is_compressed(base):
            # 丢弃压缩项：只补跑原始视频
            continue
        candidate = os.path.join(ORIGINAL_DIR, base)
        if os.path.exists(candidate):
            normalized.append(candidate)
    return normalized


def main():
    args = parse_args()
    if not os.path.exists(args.list):
        raise RuntimeError(f'缺失清单不存在: {args.list}')
    with open(args.list, 'r', encoding='utf-8') as f:
        raw_paths = [line.strip() for line in f if line.strip()]
    paths = normalize_paths(raw_paths)
    print(f'待补跑视频: {len(paths)}')

    analyzer = VideoBatchAnalyzer(config_path=args.config, api_key=args.api_key, workers=args.workers)

    success = 0
    failed = 0
    for p in paths:
        try:
            res = analyzer.process_single_video(p, args.output_dir)
            if res is None:
                failed += 1
            else:
                success += 1
        except Exception:
            failed += 1
    total = success + failed
    print(f'补跑完成：成功 {success} / 失败 {failed} / 总计 {total}')


if __name__ == '__main__':
    main()

